package com.summer.Thread;
class Clerk {
    private  int product ;
    public synchronized void producer() throws InterruptedException {
        if (product <20){
            product++;
            System.out.println(Thread.currentThread().getName()+"：开始生成第"+product+"个产品");
            notify();
        }else {
            wait();
        }
    }
    public synchronized void consumer() throws InterruptedException {
        if (product >0){
            System.out.println(Thread.currentThread().getName()+"：开始消费第"+product+"个产品");
            product--;
            notify();
        }else {
            wait();
        }
    }
}
class Producter extends Thread{
    private Clerk clerk;
    public Producter (Clerk clerk){
        this.clerk=clerk;
    }
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                clerk.producer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer extends Thread {
    private Clerk clerk;
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                clerk.consumer();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}
public  class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
       Producter producter = new Producter(clerk);
       producter.setName("生产者");
       Consumer consumer = new Consumer(clerk);
       consumer.setName("消费者");
       producter.start();
       consumer.start();
    }
}

